package com.hq.door.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hq.door.dto.Pagination;
import com.hq.door.dto.Teacher;
import com.hq.door.dto.TeacherDto;
import com.hq.door.pojo.TTeacher;
import com.hq.door.service.TTeacherService;
import com.hq.door.util.ExcelUtil;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

	@Autowired
	private TTeacherService tTeacherService;

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String fileUpload(HttpServletRequest request) {
		String result = "";
		/*
		 * response.setCharacterEncoding("UTF-8");
		 * response.setContentType("application/json;charset=utf-8");
		 */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		String path = request.getSession().getServletContext().getRealPath("");
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (item.isFormField()) {
					System.out.println("表单的参数名称：" + item.getFieldName()
							+ ",对应的参数值：" + item.getString("UTF-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						System.out.println("上传文件的大小：" + item.getSize());
						System.out.println("上传文件的类型：" + item.getContentType());
						System.out.println("上传文件的名称：" + item.getName());

						File tempFile = new File(item.getName());
						String savePath = path
								+ File.separator
								+ "backend"
								+ File.separator
								+ "doc"
								+ File.separator
								+ new SimpleDateFormat("yyyyMMdd-HHmmss")
										.format(new Date())
								+ tempFile.getName();

						item.write(new File(savePath));
						// 获取表数据
						List<Map<String, String>> list = ExcelUtil
								.readExcelOfTeachers(savePath);
						// 对表数据进行迭代筛查
						Iterator<Map<String, String>> iterator = list
								.iterator();
						// 备份遍历的前一个数据元
						Map<String, String> oldObj = null;
						// 利用HashSet过滤表数据，查重。
						HashSet<String> checkRepeat = new HashSet<>();
						while (iterator.hasNext()) {
							Map<String, String> next = iterator.next();
							// 教师名称、工号、手机号码、账号和密码为空则导入失败
							if (next.get(ExcelUtil.TCODE).equals("")
									|| next.get(ExcelUtil.TNAME).equals("")
									|| next.get(ExcelUtil.TMOBILE).equals("")
									|| next.get(ExcelUtil.TACCOUNT).equals("")) {
								if (next.get(ExcelUtil.TPASSWORD).equals("")) {
									iterator.remove();
								} else if (oldObj != null) {
									return "\"" + "导入失败，工号为："
											+ oldObj.get(ExcelUtil.TCODE)
											+ " 的教师之后存在空数据，请修改后重新提交。" + "\"";
								} else {
									return "\"" + "导入失败，表中第二行存在空数据，请修改后重新提交。"
											+ "\"";
								}
							} else if (next.get(ExcelUtil.TPASSWORD).equals("")) {
								// 若密码为空，则默认将教师工号设置成密码
								next.put(ExcelUtil.TPASSWORD,
										next.get(ExcelUtil.TCODE));
							} else {
								// 表中存在重复账号则导入失败
								if (checkRepeat.contains(next
										.get(ExcelUtil.TACCOUNT))) {
									return "\"" + "导入失败，账号 : "
											+ next.get(ExcelUtil.TACCOUNT)
											+ " 在表中已重复，请修改后重新提交。" + "\"";
								}
								// 记录非重复账号信息
								checkRepeat.add(next.get(ExcelUtil.TACCOUNT));
							}
							// 备份本次迭代数据
							oldObj = next;

						}
						result = tTeacherService.addTeacherList(list);
					} else {
						result = "没有选择上传文件!";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "上传文件不成功！";
		}
		System.out.println(result);
		return "\"" + result + "\"";
	}

	/**
	 * 添加一条教师信息
	 * 
	 * @param teacher
	 * @return
	 */
	@RequestMapping(value = "/saveteacher", method = RequestMethod.POST)
	@ResponseBody
	public int addTeacher(TeacherDto dto) {
		TTeacher transToTTeacher = TeacherDto.readTeacher(dto);
		//检验新添加的账号是否已存在
		boolean isExist =tTeacherService.checkRepeatOfTeacherAccount(transToTTeacher);
		if(isExist){
			//存在则添加教师信息失败
			return 0;
		}
		//首次添加账号默认教师工号为密码
		transToTTeacher.setPassword(transToTTeacher.getCode());
		tTeacherService.save(transToTTeacher);
		return 1;
	}

	/**
	 * 修改一条教师信息
	 * 
	 * @param teacher
	 * @return
	 */
	@RequestMapping(value = "/modifyteacher", method = RequestMethod.POST)
	@ResponseBody
	public int modifyTeacher(TeacherDto dto) {
		tTeacherService.modifyTeacherInfo(TeacherDto.readTeacher(dto));
		return 1;
	}

	/**
	 * 删除教师信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteteacher")
	@ResponseBody
	public int delete(int[] id) {
		tTeacherService.deleteselect(id);
		return 1;
	}

	/**
	 * 查询单条教师信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getteacher", method = RequestMethod.POST)
	@ResponseBody
	public Teacher get(String id) {
		TTeacher tTeacher = tTeacherService.get(Integer.valueOf(id));
		Teacher teacher = TeacherDto.writeMajor(tTeacher);
		return teacher;

	}

	/**
	 * 修改教师信息
	 * 
	 * @param teacher
	 * @return
	 */
	@RequestMapping("/updatemaster")
	public boolean update(Teacher teacher) {
		boolean res = tTeacherService.updateselect(teacher);
		return res;
	}

	@RequestMapping("/testlogin")
	public ModelAndView login(TTeacher teacher) {
		String hql = "from TTeacher t where t.code=? and t.password=?";
		Object[] values = { teacher.getCode(), teacher.getPassword() };
		List<TTeacher> list = tTeacherService.find(hql, values);
		if (list != null) {
			return new ModelAndView("backend/index");
		} else {
			return null;
		}
	}

	/**
	 * 查询教师列表
	 * 
	 * @param type
	 *            查询类型 0全部|1教师编号|2教师姓名
	 * @param para
	 *            查询参数
	 * @param pageSize
	 *            每页多少条记录
	 * @param pageStart
	 *            第几页
	 * @return
	 */
	@RequestMapping("/getByPage")
	@ResponseBody
	public Object getByPage(
			@RequestParam(value = "type", required = true) Integer type,
			@RequestParam(value = "para", required = false) String para,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "pageStart", required = false) Integer pageStart) {

		Pagination pagination = tTeacherService.getByPage(type, para,
				pageStart, pageSize);
		if (pagination == null) {
			pagination = new Pagination(0, "error", null);
		}
		pagination.setItemCount(tTeacherService.getCount(type, para));
		return pagination;

	}
	/**
	 * 修改老师的密码
	 * @param account
	 * @param possWord
	 * @return
	 */
	
	@RequestMapping(value = "/updateTeaPassWord", method = RequestMethod.POST)
	@ResponseBody
	public int updateTeaPassWord(@RequestParam(value = "account", required = true) String 

			account,
			@RequestParam(value = "password", required = true) String 

password) {

		int res = tTeacherService.updateTeaPassWord(account,password);

		return res;
	}

}
